package message;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

import event.Direction;
import event.Tank;
import user.source.TankClient;

/**
 * 
 * @author
 *
 */
public class TankNewMsg implements Msg {
	int msgType = Msg.TANK_NEW_MSG;

	Tank tank;
	TankClient tc;

	public TankNewMsg(Tank tank) {
		this.tank = tank;
	}

	public TankNewMsg(TankClient tc) {
		this.tc = tc;
	}

	@Override
	public void send(DatagramSocket ds, String ip, int udpPort) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		DataOutputStream dos = new DataOutputStream(baos);
		try {

			// 将信息类型发送出去
			dos.writeInt(msgType);
			dos.writeInt(tank.id);
			dos.writeInt(tank.x);
			dos.writeInt(tank.y);
			dos.writeInt(tank.dir.ordinal());
			dos.writeBoolean(tank.good);
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[] buffer = baos.toByteArray();

		try {
			DatagramPacket dp = new DatagramPacket(buffer, buffer.length, new InetSocketAddress(ip, udpPort));
			ds.send(dp);
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	@Override
	public void parse(DataInputStream dis) {
		try {
			int id = dis.readInt();
			// 如果坦克的id号和自己的一样，那么这个包没有用处，直接跳过
			if (tc.myTank.id == id) {
				return;
			}
			int x = dis.readInt();
			int y = dis.readInt();
			Direction dir = Direction.values()[dis.readInt()];
			boolean good = dis.readBoolean();
			System.out.println("id:" + id + "-x:" + x + "-y:" + y + "-dir:" + dir + "-good:" + good);

			// 设坦克不存在
			boolean exist = false;
			for (int i = 0; i < tc.tanks.size(); i++) {
				Tank tank = tc.tanks.get(i);
				// 若坦克存在
				if (tank.id == id) {
					exist = true;
					break;
				}
			}

			// 如果没有找到
			if (!exist) {
				// 在接受到新坦克生成命令后，发送一条自己的坦克出生声明，让后加进来的坦克能看到之前的坦克
				TankNewMsg tankMsg = new TankNewMsg(tc.myTank);
				tc.net.send(tankMsg);

				Tank tank = new Tank(x, y, good, dir, tc);
				tank.id = id;
				tc.tanks.add(tank);
			}

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
